unit testhelper;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils;

procedure StartTestPlay(ProjectFolder: String);

implementation

uses
  Dialogs, Forms, Process, LazFileUtils, LazUTF8;

const
  NwjsPaths: array [1..6] of String = (
    'nwjs',
    'share/rainbow-editor/nwjs/',
    'share/nwjs/',
    '../nwjs/',
    '../share/rainbow-editor/nwjs/',
    '../share/nwjs/'
  );

function GetNwjsDirectory: String;
  function CheckSubpathsIn(BaseDir: String): Boolean;
  var
    I: Integer;
    TestedDir: String;
  begin
    CheckSubpathsIn := False;
    SetCurrentDir(BaseDir);

    for I := Low(NwjsPaths) to High(NwjsPaths) do begin
      TestedDir := ExpandFileName(NwjsPaths[I]);
      if DirectoryExists(TestedDir) then begin
        GetNwjsDirectory := TestedDir;
        CheckSubpathsIn := True;
        break;
      end;
    end;
  end;

var
  OldCurrentDir: String;
begin
  GetNwjsDirectory := '';

  OldCurrentDir := GetCurrentDir;

  if not CheckSubpathsIn(ExtractFilePath(Application.ExeName)) then
    CheckSubpathsIn('/');

  SetCurrentDir(OldCurrentDir);
end;

procedure StartTestPlay(ProjectFolder: String);
var
  Proc: TProcess;
  I: Integer;

  { Adds a separate user data directory to ensure that RMMV's nwjs and
    Rainbow RPG Editor's nwjs don't share a profile (they are likely to have
    different versions of the nwjs, so this would result in profile errors
    during any RMMV testplay). }
  procedure AddUserDataDir;
  begin
    {$if defined(MSWINDOWS)}
      Proc.Parameters.Add('--user-data-dir='+GetEnvironmentVariableUTF8('LOCALAPPDATA') + '/Rainbow RPG Editor');
    {$elseif defined(MACOS)} //TODO: this is untested
      //see also https://wiki.freepascal.org/Multiplatform_Programming_Guide#Proper_macOS_file_locations
      Proc.Parameters.Add('--user-data-dir');
      Proc.Parameters.Add(ExpandFileNameUTF8('~/Library/Application Support/Rainbow RPG Editor/'));
    {$elseif defined(UNIX)}
      Proc.Parameters.Add('--user-data-dir=' + ExpandFileNameUTF8('~/.config/Rainbow-RPG-Editor/'));
    {$endif}
  end;

begin
  Proc := TProcess.Create(nil);
  try
    Proc.InheritHandles := False;
    Proc.Options := [];
    Proc.ShowWindow := swoShow;
    for I := 1 to GetEnvironmentVariableCount do
      Proc.Environment.Add(GetEnvironmentString(I));

    Proc.Executable := GetNwjsDirectory + 'nw';
    AddUserDataDir;
    Proc.Parameters.Add(ProjectFolder);
    Proc.Parameters.Add('test');

    Proc.Execute;
  finally
    Proc.Free;
  end;

end;

end.

